var tool = require('../tool');
var models = require('../models');
var userModel = models['user'];
module.exports = function (req, res, next) {
    if (!req.session.user && req.cookies['user'] != '') {
        try {
            var uid = tool.decrypt(req.cookies['user'], 'itravel');
        } catch (e) {
            next();
            return;
        }
        var fields = ['username', '_id', 'mail'];
        userModel.findOne({_id:uid}, fields.join(' '), function (err, doc) {
            if (err) {
                return;
            }
            console.log(doc);
            req.session.user = doc;
            res.locals.user = doc;
            next();
        });
    } else {
        if (req.session.user) {
            res.locals.user = req.session.user;
        }
        next();
    }
};